from flask import Flask,render_template, send_file, send_from_directory,json, jsonify,make_response
from flask import request
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from PIL import Image
import numpy as np
import time
import sys
import urllib.parse

def request_parse(req_data):
    if req_data.method == 'POST':
        data = req_data.json
    elif req_data.method == 'GET':
        data = req_data.args
    return data

app = Flask(__name__)
@app.route("/getUrlImage", methods=["GET","POST"])
def getImage():
    is_mobile = request.values.get("is_mobile")
    url = request.form.get("url")
    if url is None:
        url = request.values.get("url")
        url = urllib.parse.unquote(url)
    print(is_mobile,url)
    options = Options()
    if is_mobile == "True":
        mobile_emulation = {"deviceName": "iPhone 12 Pro"}
        options.add_experimental_option("mobileEmulation", mobile_emulation)
        options.add_experimental_option("excludeSwitches", ["enable-logging"])
    # options.add_argument('headless')
    driver = webdriver.Chrome(options=options)
    try:
        driver.get(url)
        # if is_mobile != "True":
        driver.maximize_window()
        # time.sleep(3)
        # width = driver.execute_script("return document.documentElement.scrollWidth")
        window_height = driver.get_window_size()['height']
        page_height = driver.execute_script("return document.documentElement.scrollHeight")
        print(window_height,page_height)
        time.sleep(1)
        driver.save_screenshot('qq.png')
        if page_height > window_height:
            n = page_height // window_height  # 需要滚动的次数
            base_mat = np.atleast_2d(Image.open('qq.png'))  # 打开截图并转为二维矩阵
            for j in range(n):
                driver.execute_script(f'document.documentElement.scrollTop={window_height*(j+1)};')
                time.sleep(.5)
                driver.save_screenshot(f'qq_{j}.png')  # 保存截图
                mat = np.atleast_2d(Image.open(f'qq_{j}.png'))  # 打开截图并转为二维矩阵
                base_mat = np.append(base_mat, mat, axis=0)  # 拼接图片的二维矩阵
            Image.fromarray(base_mat).save('./Image/image.png')
            driver.close()
            driver.quit()
            return send_file("Image/image.png",sys.path[0])
        return send_file("qq.png",sys.path[0])
    except Exception as e:
        driver.close()
        driver.quit()
        return jsonify({"code": "异常", "message": "{}".format(e)})
        
        
        

@app.route("/uploadImage", methods=["GET","POST"])
def uploadImage(request):
    code = request.values.get("code")
    taskid = request.values.get("taskid")
    orderid  = request.values.get("orderid")
    md5 = request.values.get("md5")
    message = request.values.get("message")
    print(code,taskid,orderid,md5,message)
    return jsonify({"code":"200","message":"success"})
    


if __name__ == '__main__':
    app.run()